package com.coldchain.cys.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.coldchain.common.msg.BaseResponse;
import com.coldchain.common.msg.ObjectRestResponse;
import com.coldchain.common.validator.ValidatorUtils;
import com.coldchain.cys.entity.Car;
import com.coldchain.cys.entity.Cys;
import com.coldchain.cys.mapper.CarMapper;
import com.coldchain.cys.service.ICarService;
import com.coldchain.cys.service.ICysService;
import com.fangliai.core.base.service.impl.BaseServiceImpl;
import com.fangliai.core.context.BaseContextHandler;
import com.fangliai.core.entitiy.BaseSearch;
import com.fangliai.core.entitiy.PageResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianpeng
 * @since 2018-08-28
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<CarMapper, Car> implements ICarService {
	private static final Logger log= LoggerFactory.getLogger(CarServiceImpl.class);
	@Autowired
	private ICysService cysService;


	@Override
	public BaseResponse edit(Car car) {
		try{
			ValidatorUtils.validateEntity(car);
		}catch (Exception e){
			log.error("参数验证失败{}",e.getMessage());
			return new ObjectRestResponse().error("参数错误");
		}
		if(car.getId()!=null){
			if(StringUtils.isEmpty(car.getLat())||StringUtils.isEmpty(car.getLon()) ){
				log.error("请检测设备是否正常");
				return new ObjectRestResponse().error("请检测设备是否正常");
			}
		}
		if(saveOrUpdate(car)){
			return new ObjectRestResponse().succeed("ok");
		}else {
			return new ObjectRestResponse().error("服务器异常");
		}

	}

	@Override
	public BaseResponse verify(String carId) {
		Car car=getById(carId);
		if(car==null){
			log.error("not find car by id[{}]",carId);
			return new ObjectRestResponse().error("车辆不存在");
		}
		car.setStatus(car.getStatus().equals(1)?0:1);
		if(saveOrUpdate(car)){
			return new ObjectRestResponse().succeed("ok");
		}else {
			return new ObjectRestResponse().error("服务器异常");
		}
	}

	@Override
	public BaseResponse toggleStatus(String carId) {
		Car car=getById(carId);
		if(car==null){
			log.error("not find car by id[{}]",carId);
			return new ObjectRestResponse().error("车辆不存在");
		}
		car.setIsuse(car.getIsuse().equals(1)?0:1);
		if(saveOrUpdate(car)){
			return new ObjectRestResponse().succeed("ok");
		}else {
			return new ObjectRestResponse().error("服务器异常");
		}
	}


	@Override
	public BaseResponse getCarDeviceInfo(String deviceNumber) {
		Cys cys=cysService.getById(BaseContextHandler.getCysID());
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("admin_permit", cys.getDeviceToken()) ;
		map.put("SheBeiBianHao", deviceNumber) ;

		Date nowDate = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, 0).toJdkDate(); //今天
		Date beginOfDay = DateUtil.beginOfDay(nowDate).toJdkDate();
		Date endOfDay = DateUtil.endOfDay(nowDate).toJdkDate() ;
		String startTime = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
		String endTime = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
		map.put("StartTime", startTime) ;
		map.put("EndTime", endTime) ;
		map.put("StartNo", "0") ;
		map.put("Length", "1") ;
		String result = HttpUtil.post(cys.getDeviceHttp(), map);
		JSONObject ob=JSONObject.parseObject(result);
		if(ob.getInteger("code").equals(10000)){
			return new ObjectRestResponse<>().data(ob).succeed("ok");
		}else {
			return new ObjectRestResponse<>().error(ob.getString("resultCode"));
		}

//		JSONObject jsonObject = JSONObject.parseObject(result);
//		if(!jsonObject.get("code").equals(10000)) {
//			return false ;
//		}
//		if(!jsonObject.get("message").toString().equalsIgnoreCase("success")) {
//			return false ;
//		}
//		JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("resultCode").toString());
//		if(jsonArray.size() < 1) {
//			return false ;
//		}
//		JSONObject dataJson = jsonArray.getJSONObject(0);
//		System.out.println(dataJson);
//		Date collectionTime = dataJson.get("time").equals("-") ? null : dataJson.getDate("time") ;
//		BigDecimal temperature01 = dataJson.get("temperature01").equals("-") ? null : dataJson.getBigDecimal("temperature01") ;
//		BigDecimal temperature02 = dataJson.get("temperature02").equals("-") ? null : dataJson.getBigDecimal("temperature02") ;
//		BigDecimal humidity = dataJson.get("humidity").equals("-") ? null : dataJson.getBigDecimal("humidity") ;
//		BigDecimal power = dataJson.get("power").equals("-") ? null : dataJson.getBigDecimal("power") ;
//		BigDecimal xinghaoqiangdu = dataJson.get("xinghaoqiangdu").equals("-") ? null : dataJson.getBigDecimal("xinghaoqiangdu") ;
//		car.setCollectionTime(collectionTime);
//		car.setTemperature01(temperature01);
//		car.setTemperature02(temperature02);
//		car.setHumidity(humidity);
//		car.setPower(power);
//		car.setXinghaoqiangdu(xinghaoqiangdu);

	}


	@Override
	public PageResponse<Car> search(BaseSearch<Car> search) {
		return super.search(search);
	}


}
